package com.vnp.cooking;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.zip.Inflater;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap.Config;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.RatingBar;
import android.widget.RatingBar.OnRatingBarChangeListener;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TextView;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.vnp.cooking.UIcontrols.AnimatingLinearLayout;
import com.vnp.cooking.UIcontrols.MyClickAbleImageView;
import com.vnp.cooking.UIcontrols.MyListview;
import com.vnp.cooking.UIcontrols.MyListview.OnDetectScrollListener;
import com.vnp.cooking.UIcontrols.QuickReturnListView;
import com.vnp.cooking.adapter.ListNguyenlieuAdapter;
import com.vnp.cooking.adapter.TabsAdapterKitchen;
import com.vnp.cooking.bean.ObjCookpad;
import com.vnp.cooking.bean.ObjNguyenlieu;
import com.vnp.cooking.fragmentKitchen.CoverCanhan1;
import com.vnp.cooking.fragmentKitchen.FragmentLiked;
import com.vnp.cooking.frgDetail.FrgBinhluan;
import com.vnp.cooking.httpclient.HttpClientHelper;
import com.vnp.cooking.httpclient.MyJsonHttpResponseHandler;
import com.vnp.cooking.utils.HelperListview;
import com.vnp.cooking.utils.PreferenceHelper;
import com.vnp.cooking.utils.Utils;

public class ChitietCongthucActivity extends SherlockFragmentActivity implements
		 OnClickListener, OnCheckedChangeListener, OnTouchListener {

	PreferenceHelper preferenceHelper;
	// khai bao nut back ve trang favourite
	ImageButton btnBack;
	// Khai bao nut chuyen den trang binh luan
	Button btnComment;
	View stepCook;
	ObjCookpad objCookpad = new ObjCookpad();
	ObjCookpad objRate = new ObjCookpad();

	// Khai bao cac thuoc tinh cua mon an
	ImageView imgMonan;
	TextView txtTenMonan, txtTenNguoidang, txtThoigiannau, txtTenMonAnTitle;
	TextView txtDesciption;

	// Khai bao imageLoader
	DisplayImageOptions options = new DisplayImageOptions.Builder()
			.cacheOnDisc(true).cacheInMemory(false)
			.displayer(new FadeInBitmapDisplayer(300))
			.bitmapConfig(Config.RGB_565).build();

	// rating
	RatingBar ratingBar;
	TextView titleRating;
	TextView txtCountRating;
	int countRating = 0;
	int totalTurnRate;
	float totalRateValueInt;
	Button btnRatingDone;
	ProgressBar progressBar;
	View rlRating;
	int valueRating = 0;
	
	ViewGroup ratell;

	// Dialog option
	Dialog dialog, dLiked, dPinned, dRating;

	// khai bao tabhost
	private TabHost mTabHost;
	private ViewPager mViewPager;
	private TabsAdapterKitchen mTabsAdapter;
	ImageButton btnLike, btnShowDialog;

	// Khai bao layout an di
	FrameLayout frImage;
	AnimatingLinearLayout llLayout;

	// Khai bao button tab
	Button btnNguyenlieu, btnCachlam, btnBinhluan;

	// List nguyen lieu

	ListNguyenlieuAdapter adapterNguyenlieu;
	ArrayList<ObjNguyenlieu> objNguyenlieus = new ArrayList<ObjNguyenlieu>();
	Button btnChontatca, btnChovaodicho;
	boolean isChecking = false;
	boolean isAddedDsDicho = false;
	boolean isCheckedOne = false;
	int count;
	MyClickAbleImageView btnLikeCT, btnThembst;

	int liked;
	static int pinned;
	String urlShareFB;

	// quick

	MyListview listNguyenlieu;
	View footer;
	private int mQuickReturnHeight;

	private static final int STATE_ONSCREEN = 0;
	private static final int STATE_OFFSCREEN = 1;
	private static final int STATE_RETURNING = 2;
	private int mState = STATE_ONSCREEN;
	private int mScrollY;
	private int mMinRawY = 0;

	private TranslateAnimation anim;

	int lastVisibleItem = 0;
	boolean isScrollingDown = false;

	View actionBar;
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_chi_tiet_cong_thuc);

		preferenceHelper = new PreferenceHelper(this);

		objCookpad = getIntent().getParcelableExtra("objCookpad");
		

		actionBar = (View) findViewById(R.id.actionbar);

		btnBack = (ImageButton) findViewById(R.id.btn_back);

		frImage = (FrameLayout) findViewById(R.id.fr_image);

		llLayout = (AnimatingLinearLayout) findViewById(R.id.ll_layout);

		progressBar = (ProgressBar) findViewById(R.id.progressBar1);
		txtTenMonAnTitle = (TextView) findViewById(R.id.txt_tenmonan_title);
		btnShowDialog = (ImageButton) findViewById(R.id.btn_share_cookpad);

		
		footer = (View) findViewById(R.id.footer);


		// list nguyen lieu
		listNguyenlieu = (MyListview) findViewById(R.id.list_nguyenlieu);
		addHeader();
		adapterNguyenlieu = new ListNguyenlieuAdapter(this, objNguyenlieus);
		// addFooterNguyenlieu();
		listNguyenlieu.setAdapter(adapterNguyenlieu);
		// hien thi listview on scrol view
		getChitietMonan();

//		footer.setVisibility(View.VISIBLE);
		
		setFontMain();
		init();
		/*listNguyenlieu.setOnDetectScrollListener(new OnDetectScrollListener() {

			@Override
			public void onUpScrolling() {
				// footer.setVisibility(View.VISIBLE);
				if (footer.getVisibility() == View.GONE) {
					slideToTop(footer);
				}

			}

			@Override
			public void onDownScrolling() {
				slideToBottom(footer);
			}
		});*/

	}
	
	void setFontMain(){
		txtTenMonAnTitle.setTypeface(Utils.getTypefaceRegular(ChitietCongthucActivity.this), Typeface.BOLD);
	}
	
	void setFontHeader(){
		txtTenMonan.setTypeface(Utils.getTypefaceRegular(ChitietCongthucActivity.this), Typeface.BOLD);
		txtTenNguoidang.setTypeface(Utils.getTypefaceRegular(ChitietCongthucActivity.this), Typeface.BOLD);
		txtThoigiannau.setTypeface(Utils.getTypefaceRegular(ChitietCongthucActivity.this));
		txtDesciption.setTypeface(Utils.getTypefaceRegular(ChitietCongthucActivity.this));
		btnNguyenlieu.setTypeface(Utils.getTypefaceRegular(ChitietCongthucActivity.this));
		btnCachlam.setTypeface(Utils.getTypefaceRegular(ChitietCongthucActivity.this));
		btnBinhluan.setTypeface(Utils.getTypefaceRegular(ChitietCongthucActivity.this));
		titleRating.setTypeface(Utils.getTypefaceRegular(ChitietCongthucActivity.this));
		txtCountRating.setTypeface(Utils.getTypefaceRegular(ChitietCongthucActivity.this));
	}
	

	@Override
	protected void onResume() {
		super.onResume();
		
		if (pinned == 1) {
			btnThembst.setVisibility(View.GONE);
		}
		
	}

	// To animate view slide out from top to bottom
	public void slideToBottom(View view) {
		TranslateAnimation animate = new TranslateAnimation(0, 0, 0,
				view.getHeight());
		animate.setDuration(300);
		// animate.setFillAfter(true);
		view.startAnimation(animate);
		view.setVisibility(View.GONE);
	}

	// To animate view slide out from bottom to top
	public void slideToTop(View view) {
		TranslateAnimation animate = new TranslateAnimation(0, 0,
				Utils.getScreenHeighY(ChitietCongthucActivity.this),
				Utils.getScreenHeighY(ChitietCongthucActivity.this)
						- view.getHeight());
		animate.setDuration(300);
		// animate.setFillAfter(true);
		view.startAnimation(animate);
		view.setVisibility(View.VISIBLE);
	}

	void setValue() {
			ImageLoader.getInstance().displayImage(objCookpad.getUrlImageCookpad(),
					imgMonan, options);
			if (objCookpad.getNameCookpad().length() > 20) {
				txtTenMonAnTitle.setText(objCookpad.getNameCookpad().substring(0,
						20)
						+ "...");
			} else {
				txtTenMonAnTitle.setText(objCookpad.getNameCookpad());
			}
			if (objCookpad.getNameCookpad().length() > 30) {
				txtTenMonan.setText(objCookpad.getNameCookpad().substring(0, 30)
						+ "...");
			} else {
				txtTenMonan.setText(objCookpad.getNameCookpad());
			}
			txtDesciption.setText(objCookpad.getDescriptionCookpad());

			txtThoigiannau.setText(objCookpad.getThoigianNauan());
			txtTenNguoidang.setText(objCookpad.getNamePersonCookpad());
			txtThoigiannau.setText(objCookpad.getThoigianNauan());
	}

	/*
	 * void quickReturn() {
	 * listNguyenlieu.getViewTreeObserver().addOnGlobalLayoutListener( new
	 * OnGlobalLayoutListener() {
	 * 
	 * @Override public void onGlobalLayout() { mQuickReturnHeight =
	 * footer.getHeight(); listNguyenlieu.computeScrollY(); } });
	 * 
	 * listNguyenlieu.setOnScrollListener(new OnScrollListener() {
	 * 
	 * @Override public void onScrollStateChanged(AbsListView view, int
	 * scrollState) {
	 * 
	 * }
	 * 
	 * @Override public void onScroll(AbsListView view, int firstVisibleItem,
	 * int visibleItemCount, int totalItemCount) { mScrollY = 0; int
	 * translationY = 0;
	 * 
	 * if (listNguyenlieu.scrollYIsComputed()) { mScrollY =
	 * listNguyenlieu.getComputedScrollY(); }
	 * 
	 * int rawY = mScrollY;
	 * 
	 * switch (mState) { case STATE_OFFSCREEN: if (rawY >= mMinRawY) { mMinRawY
	 * = rawY; } else { mState = STATE_RETURNING; } translationY = rawY; break;
	 * 
	 * case STATE_ONSCREEN: if (rawY > mQuickReturnHeight) { mState =
	 * STATE_OFFSCREEN; mMinRawY = rawY; } translationY = rawY; break;
	 * 
	 * case STATE_RETURNING:
	 * 
	 * translationY = (rawY - mMinRawY) + mQuickReturnHeight;
	 * 
	 * System.out.println(translationY); if (translationY < 0) { translationY =
	 * 0; mMinRawY = rawY + mQuickReturnHeight; }
	 * 
	 * if (rawY == 0) { mState = STATE_ONSCREEN; translationY = 0; }
	 * 
	 * if (translationY > mQuickReturnHeight) { mState = STATE_OFFSCREEN;
	 * mMinRawY = rawY; } break; }
	 *//** this can be used if the build is below honeycomb **/
	/*
	 * if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.HONEYCOMB) { anim = new
	 * TranslateAnimation(0, 0, translationY, translationY);
	 * anim.setFillAfter(true); anim.setDuration(0);
	 * footer.startAnimation(anim); } else {
	 * footer.setTranslationY(translationY); } } }); }
	 */

	void init() {
		// set su kien click
		btnBack.setOnClickListener(this);

		btnShowDialog.setOnClickListener(this);

		// lay so phan tu checked
		count = listNguyenlieu.getCount();

		actionBar.setOnClickListener(this);
	}

	void addHeader() {
		LayoutInflater inflater = getLayoutInflater();
		ViewGroup v = (ViewGroup) inflater.inflate(
				R.layout.header_chitiet_cong_thuc, listNguyenlieu, false);
		// khai bao vi tri cac thuooc tinh mon an
		imgMonan = (ImageView) v.findViewById(R.id.img_monan);
		txtTenMonan = (TextView) v.findViewById(R.id.txt_ten_mon_an);
		txtTenNguoidang = (TextView) v.findViewById(R.id.txt_ten_nguoi_dang);
		txtThoigiannau = (TextView) v.findViewById(R.id.txt_thoi_gian);
		txtDesciption = (TextView) v.findViewById(R.id.txt_decription);
		ratell = (ViewGroup) v.findViewById(R.id.rateLL);
		ratell.setVisibility(View.GONE);
		
		
		btnLikeCT = (MyClickAbleImageView) v.findViewById(R.id.btn_like_ct);
		btnThembst = (MyClickAbleImageView) v.findViewById(R.id.btn_thembosuutap);
		btnLikeCT.setEnabled(false);
		btnThembst.setEnabled(false);

		ratingBar = (RatingBar) v.findViewById(R.id.ratingBar);
		ratingBar.setNumStars(5);
		ratingBar.setMax(5);
		ratingBar.setStepSize((float) 0.5);
		ratingBar.setEnabled(false);
		ratingBar.setClickable(false);
		ratingBar.setFocusable(false);
		titleRating = (TextView) v.findViewById(R.id.title_danhgia);
		txtCountRating = (TextView) v.findViewById(R.id.txt_count_rate);
		btnRatingDone = (Button) v.findViewById(R.id.btn_rating_done);
		rlRating = (View) v.findViewById(R.id.rl_rating);
		// khai bao button
		btnNguyenlieu = (Button) v.findViewById(R.id.btn_nguyenlieu);
		btnCachlam = (Button) v.findViewById(R.id.btn_cachlam);
		btnBinhluan = (Button) v.findViewById(R.id.btn_binhluan);
		
		setFontHeader();

		btnRatingDone.setOnClickListener(this);

//		ratingBar.setOnRatingBarChangeListener(this);
		
		btnNguyenlieu.setOnClickListener(this);
		btnCachlam.setOnClickListener(this);
		btnBinhluan.setOnClickListener(this);
		txtTenNguoidang.setOnClickListener(this);
		rlRating.setOnClickListener(this);
		btnLikeCT.setOnClickListener(this);
		btnThembst.setOnClickListener(this);
		btnNguyenlieu.setTextColor(getResources().getColor(R.color.color_red));

		btnCachlam.setEnabled(false);
		btnBinhluan.setEnabled(false);

		ratingBar.setEnabled(false);

		listNguyenlieu.addHeaderView(v, null, false);
		setValue();
		initFontHeader();
	}
	
	void initFontHeader() {
		titleRating.setTypeface(Utils.getTypefaceRegular(ChitietCongthucActivity.this));
		txtCountRating.setTypeface(Utils.getTypefaceRegular(ChitietCongthucActivity.this));
		titleRating.setTypeface(Utils.getTypefaceRegular(ChitietCongthucActivity.this));
		txtDesciption.setTypeface(Utils.getTypefaceRegular(ChitietCongthucActivity.this));
		btnNguyenlieu.setTypeface(Utils.getTypefaceRegular(ChitietCongthucActivity.this));
		btnCachlam.setTypeface(Utils.getTypefaceRegular(ChitietCongthucActivity.this));
		btnBinhluan.setTypeface(Utils.getTypefaceRegular(ChitietCongthucActivity.this));
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {

		case R.id.actionbar:
			listNguyenlieu.smoothScrollToPosition(0);
			break;
		case R.id.btn_like_ct:
			if (liked == 1) {
				showDialogLiked();
			} else {
				likeCongthuc();
			}

			break;
		case R.id.btn_thembosuutap:
			if (pinned == 1) {
				showDialogPinned();
			} else {
				gotoBST();
			}
			break;
		case R.id.btn_back:
			finish();
			break;
		case R.id.btn_share_cookpad:
			showDialogReport();
			break;
		case R.id.rl_rating:
			showDialogDanhgia();
			break;
		case R.id.txt_ten_nguoi_dang:
			Intent c = new Intent(ChitietCongthucActivity.this,
					XemThongTinUserActivity.class);
			c.putExtra("objCookpad", objCookpad);
			v.getContext().startActivity(c);
			overridePendingTransition(R.anim.open_next, R.anim.close_main);
			break;
		// button dialog
		case R.id.btn_chiase:
			dialog.dismiss();
			shareUrlFacebook();
			break;
		case R.id.btn_themvaobosuutap:
			dialog.dismiss();
			if (pinned == 1) {
				showDialogPinned();
			} else {
				gotoBST();
			}
			break;
		case R.id.btn_thoat:
			dialog.dismiss();
			
			break;

		case R.id.btn_nguyenlieu:
			if (llLayout.getVisibility() == View.GONE) {
				llLayout.show();
			} else {
				llLayout.hide();
			}

			break;
		case R.id.btn_cachlam:
			gotoCachlam();
			break;
		case R.id.btn_binhluan:
			gotoBinhluan();
			break;
		case R.id.btn_chontatca_nguyenlieu:
			if (isChecking == false) {
				selectAllCheckbox();
			} else {
				diableSelectallCheckbox();
			}

			break;
		case R.id.btn_chovao_ds_dicho:
			if (count > 0) {
				addVaoDsDicho();
			}
			break;


		}
	}


	// show dialog chia se
	public void showDialogReport() {
		dialog = new Dialog(this, R.style.DialogSlideAnim);
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.dialog_choose_option_cookpad_detail);

		// set cac phan tu ben trong
		Button btnChiase = (Button) dialog.findViewById(R.id.btn_chiase);
		Button btnThemvaoBST = (Button) dialog
				.findViewById(R.id.btn_themvaobosuutap);
		Button btnThoat = (Button) dialog.findViewById(R.id.btn_thoat);

		WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
		lp.copyFrom(dialog.getWindow().getAttributes());
		lp.width = WindowManager.LayoutParams.MATCH_PARENT;
		lp.height = WindowManager.LayoutParams.WRAP_CONTENT;

		dialog.setCanceledOnTouchOutside(true);
		dialog.show();
		dialog.getWindow().setAttributes(lp);
		dialog.getWindow().setGravity(Gravity.BOTTOM);
		dialog.getWindow().setBackgroundDrawable(new ColorDrawable(0));

		// setOnclick
		btnChiase.setOnClickListener(this);
		btnThemvaoBST.setOnClickListener(this);
		btnThoat.setOnClickListener(this);
	}

	// Den trang binh luan
	void gotoBinhluan() {
		Intent b = new Intent(this, CommentFBActivity.class);
		b.putExtra("objCookpad", objCookpad);
		startActivity(b);
		overridePendingTransition(R.anim.open_next, R.anim.close_main);
	}

	// den trang cach lamf
	void gotoCachlam() {
		Intent c = new Intent(this, StepbyCookpadActivity.class);
		c.putExtra("objCookpad", objCookpad);
		startActivity(c);
		overridePendingTransition(R.anim.open_next, R.anim.close_main);
	}

	// add footer nguyen lieu
	void addFooterNguyenlieu() {
		View footerView = getLayoutInflater().inflate(
				R.layout.footer_list_nguyenlieu, listNguyenlieu, false);
		listNguyenlieu.addFooterView(footerView);
		btnChontatca = (Button) footerView
				.findViewById(R.id.btn_chontatca_nguyenlieu);
		btnChovaodicho = (Button) footerView
				.findViewById(R.id.btn_chovao_ds_dicho);
		btnChontatca.setOnClickListener(this);
		btnChovaodicho.setOnClickListener(this);
	}

	// select all check box
	public void selectAllCheckbox() {
		for (int i = 0; i < listNguyenlieu.getLastVisiblePosition()
				- listNguyenlieu.getFirstVisiblePosition(); i++) {

			LinearLayout itemLayout = (LinearLayout) listNguyenlieu
					.getChildAt(i);
			/*
			 * CheckBox cb = (CheckBox) itemLayout.findViewById(R.id.checkbox);
			 * cb.setChecked(true);
			 */
		}
		btnChontatca.setText("Bá»� chá»�n táº¥t cáº£");
		isChecking = true;
	}

	public void diableSelectallCheckbox() {

		for (int i = 0; i < listNguyenlieu.getLastVisiblePosition()
				- listNguyenlieu.getFirstVisiblePosition(); i++) {

			LinearLayout itemLayout = (LinearLayout) listNguyenlieu
					.getChildAt(i);
			/*
			 * CheckBox cb = (CheckBox) itemLayout.findViewById(R.id.checkbox);
			 * cb.setChecked(false);
			 */
		}
		btnChontatca.setText("Chá»�n táº¥t cáº£");
		isChecking = false;
	}

	// xu li phan cho vao ds di cho
	public void addVaoDsDicho() {
		btnChovaodicho.setText("Ä�Ã£ cho vÃ o ds di chá»£");
		isAddedDsDicho = true;
	}

	public void xoaboKhoiDsDicho() {
		btnChovaodicho.setText("Cho vÃ o ds di chá»£");
		isAddedDsDicho = false;
	}

	@Override
	public void onCheckedChanged(RadioGroup group, int checkedId) {
	}

	// GOTO THEM VAO BO SUU TAP
	public void gotoBST() {
		Intent t = new Intent(this, ThemVaoBoSuuTapActivity.class);
		t.putExtra("objCookpad", objCookpad);
		startActivity(t);
		overridePendingTransition(R.anim.open_next, R.anim.close_main);
	}

	// get chi tiet monan
	void getChitietMonan() {
		HttpClientHelper httpClientHelper = new HttpClientHelper(
				new MyJsonHttpResponseHandler() {

					@Override
					public void onFailure(Throwable error) {
						super.onFailure(error);
					}

					@Override
					public void onSuccess(JSONObject re) {
						try {
							int status = re.getInt("status");
							if (status == 200) {
								
								ratell.setVisibility(View.VISIBLE);
								JSONObject jo = re.getJSONObject("data");
								Log.i("DATA", "DETAIL CT: " + jo.toString());
								objCookpad.setId(jo.getString("id"));
								totalTurnRate = jo.getInt("rating_total_count");
								totalRateValueInt = (float) jo.getDouble("rating_avg_value");

								Log.i("DATA", "Gia tri luot danh gia: "
										+ totalTurnRate);
								Log.i("DATA", "Gia tri sao: "
										+ totalRateValueInt);

								liked = jo.getInt("liked");
								pinned = jo.getInt("pinned");
								
								if (liked == 1) {
									btnLikeCT.setVisibility(View.GONE);
								}
								
								if (pinned == 1) {
									btnThembst.setVisibility(View.GONE);
								}

								// set gia tri cho rating bar

								ratingBar.setRating(totalRateValueInt);
								txtCountRating.setText("(" + "" + totalTurnRate
										+ ")");

								objCookpad.setIdNamePerson(jo.getJSONObject(
										"author").getString("id"));
								objCookpad.setRatingTotalCount(totalTurnRate);
								objCookpad.setRatingAg(totalRateValueInt);
								titleRating.setVisibility(View.VISIBLE);
								btnRatingDone.setVisibility(View.GONE);
								objCookpad.setUrlComment(jo
										.getString("urlCommendFb"));
								urlShareFB = jo.getString("urlShareFb");
								objCookpad.setUrlShareFB(urlShareFB);

								// get nguyen lieu
								JSONObject materials = jo
										.getJSONObject("material");
								Iterator<String> keys = materials.keys();
								JSONArray mt = new JSONArray();
								while (keys.hasNext()) {
									String key = keys.next();
									String value = materials.optString(key);
									// add value to JSONArray from JSONObject
									mt.put(value);
									ObjNguyenlieu objNguyenlieu = new ObjNguyenlieu();
									objNguyenlieu.setNguyenLieu(key);
									objNguyenlieu.setSoLuong(value);
									objNguyenlieus.add(objNguyenlieu);
									Log.i("DATA", "" + key + " " + "" + value);
								}
							}
							adapterNguyenlieu.notifyDataSetChanged();
							progressBar.setVisibility(View.GONE);
							btnShowDialog.setVisibility(View.VISIBLE);

							btnLikeCT.setEnabled(true);
							btnThembst.setEnabled(true);

							btnCachlam.setEnabled(true);
							btnBinhluan.setEnabled(true);

							ratingBar.setEnabled(true);
							
							
							
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}

				});
			httpClientHelper.getDetailCongthuc(objCookpad.getId(),
					preferenceHelper.getID());
		
	}

	// Danh gia cong thuc
	public void ratingCongthuc(final int value) {
		HttpClientHelper httpClientHelper = new HttpClientHelper(
				new MyJsonHttpResponseHandler() {

					@Override
					public void onFailure(Throwable error) {
						super.onFailure(error);
					}

					@Override
					public void onSuccess(JSONObject re) {
						int status;
						try {
							status = re.getInt("status");
							if (status == 200) {
								progressBar.setVisibility(View.GONE);
								btnShowDialog.setVisibility(View.VISIBLE);
								Log.i("DATA", "DANH GIA CONG THUC THANH CONG");
								float data = (float) re.getDouble("data");
								ratingBar.setRating(data);
								txtCountRating.setText("(" + "" + (totalTurnRate+1)+ ")");
							}
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

					}
				});

		httpClientHelper.ratingCongthuc(preferenceHelper.getID(),
				objCookpad.getId(), value);
	}

	void likeCongthuc() {
		HttpClientHelper httpClientHelper = new HttpClientHelper(
				new MyJsonHttpResponseHandler() {

					@Override
					public void onFailure(Throwable error) {
						super.onFailure(error);
					}

					@Override
					public void onSuccess(JSONObject re) {
						int status;
						try {
							status = re.getInt("status");
							if (status == 200) {
								btnLikeCT.setVisibility(View.GONE);
								Log.i("DATA", "DA like thanh cong");
							} else {
								Log.i("DATA", "Like that bai");
							}
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

					}
				});
		httpClientHelper.likeCongthuc(preferenceHelper.getID(),
				objCookpad.getId());
	}

	void showDialogLiked() {
		dLiked = new Dialog(this, R.style.DialogSlideAnimLeft);
		dLiked.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dLiked.setContentView(R.layout.dialog_da_thich);

		Button btnTieptucThem = (Button) dLiked
				.findViewById(R.id.btn_tieptuc_bst);
		dLiked.getWindow().setBackgroundDrawable(new ColorDrawable(0));
		dLiked.setCanceledOnTouchOutside(true);
		dLiked.getWindow().setGravity(Gravity.CENTER);
		dLiked.show();

		// setonclick
		btnTieptucThem.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dLiked.dismiss();
			}
		});
	}
	
	void showDialogPinned() {
		dPinned = new Dialog(this, R.style.DialogSlideAnimLeft);
		dPinned.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dPinned.setContentView(R.layout.dialog_da_them_bst);

		Button btnTieptucThem = (Button) dPinned
				.findViewById(R.id.btn_tieptuc_bst);

		dPinned.getWindow().setBackgroundDrawable(new ColorDrawable(0));
		dPinned.setCanceledOnTouchOutside(true);
		dPinned.getWindow().setGravity(Gravity.CENTER);
		dPinned.show();

		// setonclick
		btnTieptucThem.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dPinned.dismiss();
			}
		});
	}

	// share link to fb
	public void shareUrlFacebook() {
		/*
		 * Facebook - "com.facebook.katana" Twitter - "com.twitter.android"
		 * Instagram - "com.instagram.android" Pinterest - "com.pinterest"
		 */
		// getPackageName() from Context or Activity object
		final String appPackageName = "com.facebook.katana";
		Intent intent = getPackageManager().getLaunchIntentForPackage(
				"com.facebook.katana");
		if (intent != null) {
			Intent share = new Intent(android.content.Intent.ACTION_SEND);
			share.setType("text/plain");
			share.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
			// add data
			share.putExtra(Intent.EXTRA_TEXT, objCookpad.getUrlShareFB());
			startActivity(Intent.createChooser(share, "Anuong.net"));

		} else {

			try {
				startActivity(new Intent(Intent.ACTION_VIEW,
						Uri.parse("market://details?id=" + appPackageName)));
			} catch (android.content.ActivityNotFoundException anfe) {
				startActivity(new Intent(
						Intent.ACTION_VIEW,
						Uri.parse("http://play.google.com/store/apps/details?id="
								+ appPackageName)));
			}
		}
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		switch (v.getId()) {
		case R.id.rl_rating:
			if (event.getAction() == MotionEvent.ACTION_UP) {
				showDialogDanhgia();
			}
			break;

		default:
			break;
		}
		return false;
	}
	
	// show dialog danh gia
	void showDialogDanhgia(){
		dRating = new Dialog(this, R.style.DialogSlideAnim);
		dRating.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dRating.setContentView(R.layout.dialog_rating_star);

		// set cac phan tu ben trong
		Button btn1 = (Button) dRating.findViewById(R.id.btn_1);
		Button btn2 = (Button) dRating.findViewById(R.id.btn_2);
		Button btn3 = (Button) dRating.findViewById(R.id.btn_3);
		Button btn4 = (Button) dRating.findViewById(R.id.btn_4);
		Button btn5 = (Button) dRating.findViewById(R.id.btn_5);
		
		Button btnThoat = (Button) dRating.findViewById(R.id.btn_thoat);

		WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
		lp.copyFrom(dRating.getWindow().getAttributes());
		lp.width = WindowManager.LayoutParams.MATCH_PARENT;
		lp.height = WindowManager.LayoutParams.WRAP_CONTENT;

		dRating.setCanceledOnTouchOutside(true);
		dRating.show();
		dRating.getWindow().setAttributes(lp);
		dRating.getWindow().setGravity(Gravity.BOTTOM);
		dRating.getWindow().setBackgroundDrawable(new ColorDrawable(0));

		// setOnclick
		btn1.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				progressBar.setVisibility(View.VISIBLE);
				btnShowDialog.setVisibility(View.GONE);
				valueRating = 1;
				ratingCongthuc(1);
				dRating.dismiss();
			}
		});
		btn2.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				valueRating = 2;
				progressBar.setVisibility(View.VISIBLE);
				btnShowDialog.setVisibility(View.GONE);
				ratingCongthuc(2);
				dRating.dismiss();
			}
		});
		btn3.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				valueRating = 3;
				progressBar.setVisibility(View.VISIBLE);
				btnShowDialog.setVisibility(View.GONE);
				ratingCongthuc(3);
				dRating.dismiss();
			}
		});
		btn4.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				valueRating = 4;
				progressBar.setVisibility(View.VISIBLE);
				btnShowDialog.setVisibility(View.GONE);
				ratingCongthuc(4);
				dRating.dismiss();
			}
		});
		btn5.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				valueRating = 5;
				progressBar.setVisibility(View.VISIBLE);
				btnShowDialog.setVisibility(View.GONE);
				ratingCongthuc(5);
				dRating.dismiss();
			}
		});
		btnThoat.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				dRating.dismiss();
			}
		});
	}
}
